package com.chebaohui.iqs.service.impl.deal.taiping;

import java.io.ByteArrayInputStream;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chebaohui.iqs.config.ResultCode;

/**
 * 处理返回xml报文工具类
 * 
 * @author xielonghai
 * @version 2016-07-01
 */
public class XMLTool {

	/**
	 * 调太平接口返回数据 head部处理判断
	 * 
	 * @param el
	 * @return
	 */
	public static ResTaiPing responsejudge(Element el) {
		if (null == el) {
			return new ResTaiPing(ResultCode.N02, "XMLTool.responsejudge传入数据为空", "XMLTool.responsejudge传入数据为空");
		}

		try {
			JSONObject obj = new JSONObject();
			Element head = (Element) el.getChildren("head").get(0);
			List<?> headList = head.getChildren();
			for (int i = 0; i < headList.size(); i++) {
				obj.put(((Element) headList.get(i)).getName(), ((Element) headList.get(i)).getValue());
			}

			if ("S".equals(obj.getString("status").trim())) {
				// log.info(value + "-<head部处理判断>response--Head返回报文Head提取S成功!");
				return new ResTaiPing(obj);

			} else if ("F".equals(obj.getString("status").trim())) {
				// log.error(value + "-<head部处理判断>response--Head返回报文Head提取F失败:"
				// + obj.toJSONString());
				String errMsg = errorMsgView(el);
				if (!"".equals(errMsg.trim())) {
					// log.error(value + "-<head部处理判断>提取F失败详细:" + errMsg);
					errMsg = "," + errMsg;
				}

				// log.error(value +
				// "-<head部处理判断>response--Head返回报文Head提取F失败code:" +
				// obj.getString("errCode") + ",errMsg:"
				// + obj.getString("errMsg"));
				return new ResTaiPing(ResultCode.N04, obj.getString("errMsg") + "," + errMsg,
						obj.getString("errMsg") + "," + errMsg);
			} else {
				// log.error(value +
				// "-<head部处理判断>response--Head返回报文Head提取出现错误status:" +
				// obj.toJSONString());
				return new ResTaiPing(ResultCode.N02, "XMLTool.responsejudge返回报文Head提取出现错误status:" + obj.toJSONString(),
						"XMLTool.responsejudge返回报文Head提取出现");
			}

		} catch (Exception e) {
			// log.error(value +
			// "-<head部处理判断>XMLTool.responsejudge返回报文Head处理异常：" + e);
			return new ResTaiPing(ResultCode.N02, "XMLTool.responsejudge返回报文Head处理异常:" + e.getMessage(),
					"XMLTool.responsejudge返回报文Head处理异常:" + e.getMessage());
		}
	}

	/***
	 * 获取errMsg的详细信息
	 * 
	 * @return
	 */
	private static String errorMsgView(Element el) {
		String error = "";
		try {
			Element body = (Element) el.getChildren("body").get(0);
			@SuppressWarnings("unchecked")
			List<Element> backCityMsgs = body.getChildren("message");
			for (Element kl : backCityMsgs) {
				@SuppressWarnings("unchecked")
				List<Element> msgs = kl.getChildren();
				for (Element kj : msgs) {
					if (kj.getName().equals("Field"))
						error = error + "险别:" + kj.getValue() + "%";
					else if (kj.getName().equals("FieldGroup"))
						error = error + "错误原因:" + kj.getValue() + "%";
					else if (kj.getName().equals("MsgDesc"))
						error = error + "错误详细原因:" + kj.getValue() + "%";
					else
						error = error + "其他字段" + kj.getName() + ":" + kj.getValue() + "%";
				}
				error = error + ";";
			}
		} catch (Exception e) {
			error = "..异常:" + e.getMessage();
		}
		return error;
	}

	/****
	 * 获取body下 bodyCode的值
	 * 
	 * @param el
	 * @param bodyCode
	 * @return
	 */
	public static ResTaiPing responseBody(Element el, String[] bodyCode) {
		if (null == el) {
			// log.error(value + "-<获取body下
			// bodyCode的值处理>response--Body返回报文Body提取--传入数据为空");
			return new ResTaiPing(ResultCode.N02, "XMLTool.responseBody传入数据为空", "XMLTool.responseBody传入数据为空");
		}
		try {
			JSONObject obj = new JSONObject();
			Element body = (Element) el.getChildren("body").get(0);

			for (String key : bodyCode) {

				// log.info(value + "-<获取body下 bodyCode:" + key + ",的值处理>开始");

				@SuppressWarnings("unchecked")
				List<Element> backCityMsgs = body.getChildren(key);
				JSONArray arr = new JSONArray();

				for (Element kl : backCityMsgs) {
					JSONObject city = new JSONObject();
					@SuppressWarnings("unchecked")
					List<Element> msgs = kl.getChildren();
					for (Element kj : msgs) {
						city.put(kj.getName(), kj.getValue());
					}
					arr.add(city);
				}

				obj.put(key, arr);
			}
			// log.info(value + "-<获取body下 bodyCode的值处理>response--获取body下
			// bodyCode的值获取成功！");
			return new ResTaiPing(obj);
		} catch (Exception e) {
			// log.error(value + "-<获取body下
			// bodyCode的值处理>--response--Body返回报文Body处理,处理异常:" + e);
			return new ResTaiPing(ResultCode.N02, "XMLTool.responseBody返回报文Body处理,处理异常:" + e.getMessage(),
					"XMLTool.responseBody返回报文Body处理异常:" + e.getMessage());
		}

	}

	/** 将xmlString转化为Element 为后续操作准备 **/
	public static Element toElement(String xml) {
		try {
			SAXBuilder builder = new SAXBuilder(false);
			Document document = builder.build(new ByteArrayInputStream(xml.getBytes("UTF-8")));
			return document.getRootElement();
		} catch (Exception e) {
			// log.error(value + "<将xmlString转化为Element>response--Deal返回报文处理错误"
			// + e);
			return null;
		}
	}
}
